package com.tom.demo.component;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tom.demo.common.constant.CacheConstants;
import com.tom.demo.common.constant.Constants;
import com.tom.demo.common.utils.RedisUtil;
import com.tom.demo.security.DetailsUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 */
@Slf4j
@Component
public class TokenComponent {
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public DetailsUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = request.getHeader(header);
        if (StringUtils.hasText(token)) {
            return this.parseToken(token);
        }
        return null;
    }

    /**
     * 创建令牌
     * @return
     */
    public String createToken(String uuid) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, uuid);
        // 创建jwt中头部信息
        claims.put("Type", "Jwt");
        claims.put("alg", "HS256");
        return JWTUtil.createToken(claims,secret.getBytes());
    }
    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private DetailsUser parseToken(String token) {
        boolean verify = JWTUtil.verify(token, secret.getBytes());
        if(verify){
            log.info("<<==================>>token未被修改过,接下来检验token是否过期<<==================>>");
            JWT jwt = JWTUtil.parseToken(token);
            //解析对应的权限以及用户信息
            String uuid = (String)jwt.getPayload(Constants.LOGIN_USER_KEY);
            //调用getTokenKey，返回redis中对应的key  login_tokens:uuid
            String userKey = this.getTokenKey(uuid);
            Object cacheObject = redisUtil.getCacheObject(userKey);
            if(cacheObject != null){
                DetailsUser detailsUser = objectMapper.convertValue(cacheObject, DetailsUser.class);
                redisUtil.setCacheObject(CacheConstants.LOGIN_TOKEN_KEY+uuid,detailsUser,expireTime, TimeUnit.MINUTES);
                log.info("<<==================>>token重新刷新时间<<==================>>");
                return detailsUser;
            }else {
                log.error("<<==================>>token已过期了,需要重新登录<<==================>>");
            }

        }else {
            log.error("<<==================>>token校验错误，非法token<<==================>>");
        }
        return null;
    }


    /**
     * 获取redis中存储的key  login_tokens:uuid
     * @param uuid
     * @return
     */
    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 退出登录
     */
    public void removeLoginUser(HttpServletRequest request){
        String token = request.getHeader(header);
        if(StringUtils.hasText(token)){
            //解析对应的权限以及用户信息
            JWT jwt = JWTUtil.parseToken(token);
            String uuid = (String)jwt.getPayload(Constants.LOGIN_USER_KEY);
            //调用getTokenKey，返回redis中对应的key  login_tokens:uuid
            String userKey = this.getTokenKey(uuid);
            redisUtil.deleteObject(userKey);
            log.info("<<==================>>清除token,退出登录成功<<==================>>");
        }
    }
}
